<template>
  <div class="home">
    <div class="title-container">
      <div class="search-content">
        <el-form :model="searchModel" :inline="true">
          <el-form-item>
            <el-input
              v-model="searchModel.userName"
              :disabled="detailsDisabled"
              placeholder="请输入用户姓名"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchModel.status" placeholder="请选择状态">
              <el-option
                v-for="item in selectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="searchClick"
              size="medium"
            >搜索
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <el-card>
      <div class="addAccount">
        <perButton label="新建账户" type="primary" icon="el-icon-plus" size="medium" perms="USER_ADD"
                   @click="handlerAccount"></perButton>
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh"
        >刷新
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        class="elTable"
        ref="tableRef"
      >
        <el-table-column type="index" label="序号" width="50" align="center"/>
        <el-table-column prop="userName" label="用户姓名" align="center"/>
        <el-table-column prop="roleName" label="角色名称" align="center"/>
        <el-table-column prop="accountPhone" label="登陆账号" align="center" width="180"/>
        <el-table-column prop="isFirst" label="是否为初始密码" align="center" width="130">
          <template slot-scope="{ row }">
            <span v-if="row.isFirst == 1">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="accountType"
          label="正常/停用状态"
          align="center"
          width="130"
        >
          <template #default="{ row }">
            <span v-if="row.status == 1" style="color: #07c160">正常</span>
            <span v-else>停用</span>
          </template>
        </el-table-column>
        <el-table-column prop="createByName" label="角色属性" align="center"></el-table-column>
        <el-table-column prop="createByName" label="介绍人" align="center"></el-table-column>
        <el-table-column prop="createByName" label="创建人" align="center"></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="170">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column prop="updateByName" label="更新人" align="center"></el-table-column>
        <el-table-column label="更新时间" align="center" prop="createTime" width="170">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400" align="center">
          <template #default="{ row }">
            <perButton label="编辑" type="warning" size="mini" :disabled="row.userCode == 'US001'" perms="USER_EDIT"
                       @click="handlerEdit(row)"></perButton>

            <perButton label="重置密码" type="danger" size="mini" :disabled="row.userCode == 'US001'" perms="USER_RESTPWD"
                       @click="handlerReset(row)"></perButton>
            <div class="status">
              <perButton v-if="row.status == '0'" label="启用" type="success" size="mini"
                         :disabled="row.userCode == 'US001'" perms="USER_PROHIBIT"
                         @click="handlerStatus(row)"></perButton>
              <perButton v-else label="禁用" type="danger" size="mini" :disabled="row.userCode == 'US001'"
                         perms="USER_PROHIBIT"
                         @click="handlerStatus(row)"></perButton>
            </div>
            <perButton label="删除" type="danger" size="mini" :disabled="row.userCode == 'US001'" perms="USER_DEL"
                       @click="handlerDelete(row)"></perButton>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="pagination"
        :total="count"
        :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="pagination"
      />
    </el-card>
    <!-- 弹框 -->

    <yc-dialog ref="ycDialog" :dialogTitle="dialogTitle" :centerTitle="centerTitle">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="accountModelRef"
            :rules="rules"
            :model="newAccountModel"
            label-width="90px"
          >
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-model="newAccountModel.userName"
                :disabled="detailsDisabled"
              />
            </el-form-item>
            <el-form-item label="角色名称" prop="roleCode">
              <el-select
                v-model="newAccountModel.roleCode"
                :disabled="detailsDisabled"
              >
                <el-option
                  v-for="item in userData"
                  :key="item.roleCode"
                  :label="item.roleName"
                  :value="item.roleCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="手机号码" prop="accountPhone">
              <el-input
                type="number"
                v-model="newAccountModel.accountPhone"
                :disabled="detailsDisabled"
              />
            </el-form-item>
            <el-form-item label="行业属性" prop="remark2">
              <el-select v-model="newAccountModel.remark2" multiple class="w-100" placeholder="请选择">
                <el-option
                  v-for="(item,index) in checkboxList"
                  :key="index"
                  :label="item.configValue"
                  :value="item.configValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false"
        >取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 封装操作后弹框 -->
    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import {
    queryAccountPage,
    updateLAccount,
    ResetPassword,
    deleteAccount,
    deactivate,
    insertUser,
    queryRole
  } from "@/api/userControl/account"
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"

  export default {
    data() {
      return {
        userData: [],
        isGlobalMessageShow: false,
        isGlobalMessageBoxShow: false,
        messageTitleDes: "",
        message: "",
        messageBoxSaveShow: false,
        tableData: [],
        count: 0,
        pageIndex: 1,
        pageSize: 20,
        drawerTitle: "账户详情",
        detailsDisabled: false, //详情 如果为true代表禁用状态
        selectOptions: [
          {
            label: "正常/停用状态（全部）",
            value: null
          },
          {
            label: "正常",
            value: 1
          },
          {
            label: "禁用",
            value: 0
          }
        ],
        searchModel: {
          userName: "",
          status: null //正常/停用状态（全部）
        },
        newAccountModel: {
          userName: "",
          roleName: "",
          accountPhone: "",
          id: 0,
          roleCode: "",
          remark2: []
        },
        permersion: {
          add: "true",
          del: "true",
          update: "true"
        },
        loading: false,
        dialogTitle: "",
        centerTitle: "",
        rules: {
          userName: [{ required: true, message: "请输入账号", trigger: "blur" }],
          roleCode: [
            { required: true, message: "请选择角色", trigger: "change" }
          ],
          accountPhone: [
            { required: true, trigger: "blur", message: "请输入手机号码" }
          ],
          remark2: [
            { required: true, message: "请选择行业属性", trigger: "change" }
          ]
        },
        checkboxList: [
          { configValue: "全部", configKey: "全部" }
        ],
        addOrUpdateLoading: false
      }
    },
    components: {
      ycDialog,
      perButton
    },
    created() {

      this.getAccountData()
      this.queryRole()
    },
    methods: {
      async queryRole() {
        const data = await queryRole()
        this.userData = data.object
      },
      /**
       * 获取表格方法
       */
      async getAccountData(pageIndex = 1, pageSize = 20, tableInfo) {
        this.loading = true
        if (tableInfo) {
          const { userName, status } = tableInfo
          const { object } = await queryAccountPage({
            pageIndex,
            pageSize,
            userName,
            status
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        } else {
          const { object } = await queryAccountPage({
            pageIndex,
            pageSize
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        }
      },
      pagination(pageItem) {
        this.getAccountData(pageItem.page, pageItem.limit)
      },

      /**
       * 修改按钮
       */
      handlerEdit(row) {
        this.dialogTitle = "编辑"
        this.centerTitle = "编辑"

        this.addOrUpdateLoading = false
        this.getJYSXList()
        this.$refs.ycDialog.dialogVisible = true
        if (this.$refs.accountModelRef) {
          this.$refs.accountModelRef.clearValidate()
          this.$refs.accountModelRef.resetFields()
        }
        this.detailsDisabled = false
        this.newAccountModel.userName = row.userName
        this.newAccountModel.roleCode = row.roleCode
        this.newAccountModel.accountPhone = row.accountPhone
        this.newAccountModel.remark2 = row.remark2.split("、")
        this.newAccountModel.id = row.id
      },
      /**
       * 重置按钮
       */
      async handlerReset({ id }) {
        this.$confirm("确定重置密码吗", "重置操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        }).then(async () => {
          const { message } = await ResetPassword({ id })
          if (message == "重置成功") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },
      /**
       * 启用或者禁用按钮
       */
      async handlerStatus({ id, status }) {
        const confirmMessageMap = status == 1 ? "确定禁用吗" : "确定启用吗"
        this.$confirm(confirmMessageMap, "禁用/启用操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        }).then(async () => {
          const { message } = await deactivate({ id })
          if (message == "操作成功") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },
      /**
       * 删除按钮
       */
      async handlerDelete({ id }) {
        this.$confirm("确定删除此账户吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const { message } = await deleteAccount({ id })
          if (message == "删除成功") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },

      // 搜索按钮
      async searchClick() {
        this.getAccountData(1, 20, this.searchModel)
      },
      

      /**
       * 新建账户
       * */
      async handlerAccount() {
        this.dialogTitle = "添加"
        this.centerTitle = "添加"
        this.detailsDisabled = false
        this.addOrUpdateLoading = false
        this.getJYSXList()
        this.$refs.ycDialog.dialogVisible = true
        Object.keys(this.newAccountModel).forEach((item) => {
          this.newAccountModel[item] = ""
        })
        if (this.$refs.accountModelRef) {
          this.$refs.accountModelRef.clearValidate()
          this.$refs.accountModelRef.resetFields()
        }
      },
      dialogSave() {
        this.$refs.accountModelRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true
            if (this.detailsDisabled) {
              // 详情的确定
              this.$refs.ycDialog.dialogVisible = false
            } else if (this.newAccountModel.id) {
              const { userName, accountPhone, remark2, id, roleCode } = this.newAccountModel
              const { message, status } = await updateLAccount({
                userName,
                roleCode,
                accountPhone,
                id,
                remark2: remark2.join("、")
              })
              if (status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            } else {
              const { userName, accountPhone, remark2, roleCode } = this.newAccountModel
              const { message, status } = await insertUser({
                userName,
                roleCode,
                accountPhone,
                remark2: remark2.join("、")
              })
              if (status == 200) {
                this.getAccountData(1, 20)
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            }
            this.addOrUpdateLoading = false
          }
        })
      },
      /**
       * 刷新
       */
      refresh() {
        this.searchModel = {
          userName: "",
          status: null
        }
        this.getAccountData()
      },
      /**
       * globalMessage的知道按钮的方法
       * */
      receive() {
        this.isGlobalMessageShow = false
      },
      async messageBoxSave(show) {
        this.messageBoxSaveShow = show
      }
    }
  }
</script>

<style lang="scss" scoped>
  .status {
    display: inline-block;
    padding: 0 10px;
  }

  .title-container {
    display: flex;
    justify-content: flex-end;
    height: 60px;

    .search-content {
      margin-left: 20px;
      display: flex;
    }

    .addAccount {
      margin: 10px 20px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }

  .content {
    height: 600px;

    .drawer-title {
      font-weight: 400;
      font-size: 24px;
      color: #000000;
      text-align: center;
      padding: 36px 0;
    }

    .form {
      padding: 0 10px;
    }
  }

  .footer {
    height: 360px;
    display: flex;
    align-items: flex-end;
    // justify-content: st-end;
    padding: 5px 20px;
  }
</style>
